package com.jiji.miaosha.controller;


import com.alibaba.druid.util.StringUtils;
import com.jiji.miaosha.controller.viewobject.UserVO;
import com.jiji.miaosha.error.BusinessException;
import com.jiji.miaosha.error.EmBusinessError;
import com.jiji.miaosha.service.UserService;
import com.jiji.miaosha.service.model.UserModel;
import com.jiji.miaosha.util.EncodeUtil;
import com.jiji.miaosha.util.ResultVOUtil;
import com.jiji.miaosha.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@RestController
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    //用户登录接口
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    private ResultVO login(@RequestParam(name = "telephone") String telephone,
                           @RequestParam(name = "password") String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        UserModel userModel = userService.validateLogin(telephone, EncodeUtil.encodeByMD5(password));
        httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        httpServletRequest.getSession().setAttribute("LOGIN_USER", userModel);
        return ResultVOUtil.success();
    }

    //用户注册接口
    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    private ResultVO register(@RequestParam(name = "telephone") String telephone,
                              @RequestParam(name = "otpCode") String otpCode,
                              @RequestParam(name = "name") String name,
                              @RequestParam(name = "gender") Integer gender,
                              @RequestParam(name = "age") Integer age,
                              @RequestParam(name = "password") String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //验证手机号与对应的otpcode相符合
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute("telephone");
        if (!StringUtils.equals(inSessionOtpCode, otpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"短信验证码不符合");
        }
        //用户注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));
        userModel.setAge(age);
        userModel.setTelephone(telephone);
        userModel.setRegisterMode("byphone");
        userModel.setEncrptPassword(EncodeUtil.encodeByMD5(password));
        userService.register(userModel);
        return ResultVOUtil.success();
    }

    //用户获取otp短信
    @RequestMapping(value = "/getotp", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    private ResultVO getOtp(@RequestParam(name = "telephone") String telephone) {
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);
        httpServletRequest.getSession().setAttribute("telephone", otpCode);
        System.out.println(telephone + "," + otpCode);
        return ResultVOUtil.success();
    }

    @GetMapping("/test")
    private ResultVO getUserById(@RequestParam(name = "id") Integer id) {
        return ResultVOUtil.success(userService.getUserById(id));
    }

    @RequestMapping("/get")
    private ResultVO getUser(@RequestParam(name = "id") Integer id) {
        //调用service服务获取对应id的用户对象并返回给前端
        return ResultVOUtil.success(convertFromModel(userService.getUserById(id)));
    }

    private UserVO convertFromModel(UserModel userModel) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel, userVO);
        return userVO;
    }
}
